package com.taptech.doufu.net.retrofit.file;
import com.taptech.doufu.net.retrofit.RxBus;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;

/**
 * Created by Wyatt on 2017/10/19/019.
 */

public class FileResponseBody extends ResponseBody{

    private Response response;

    public FileResponseBody(Response response) {
        this.response = response;
    }

    @Override
    public MediaType contentType() {
        return response.body().contentType();
    }

    @Override
    public long contentLength() {
        return response.body().contentLength();
    }

    @Override
    public BufferedSource source() {
        return Okio.buffer(new ForwardingSource(response.body().source()) {
            long bytesReaded = 0;
            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                bytesReaded += bytesRead==-1?0:bytesRead;
                RxBus.getDefault().post(new FileLoadingBean(contentLength(),bytesReaded));

                return bytesRead;
            }
        });
    }
}
